package com.solution.admin.customer.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.auth.constants.AuthConstants.IS_DELETE;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.entity.CustomerExternalEntity;
import com.solution.admin.customer.entity.DeliveryAddressEntity;
import com.solution.admin.customer.service.CompanyService;
import com.solution.admin.customer.service.CustomerExternalService;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.customer.service.DeliveryAddressService;
import com.solution.admin.finance.wallet.entity.WalletEntity;
import com.solution.admin.finance.wallet.service.WalletService;
import com.solution.admin.point.constants.PointConstants;
import com.solution.admin.point.constants.PointConstants.PointOperateFlag;
import com.solution.admin.point.constants.PointConstants.PointOperateType;
import com.solution.admin.point.entity.PointEntity;
import com.solution.admin.point.service.PointService;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.constants.PublicStatus.STATUS;
import com.solution.common.constants.PublicStatus.USER_APPROVE_STATUS;
import com.solution.common.controller.BaseController;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;

/**
 * 客户信息web控制层
 * 
 * @author solin
 * @date 2017-09-22 11:35:12
 */
@RequestMapping("/customer")
@Controller
public class CustomerController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(CustomerController.class);

	@Autowired
	private CustomerService customerService;

	@Autowired
	private CompanyService companyService;

	@Autowired
	private CustomerExternalService customerExternalService;

	@Autowired
	private DeliveryAddressService deliveryAddressService;

	@Autowired
	private PointService pointService;
	
	@Autowired
    private KeyMapService keyMapService;
	
	@Autowired
	private WalletService walletService;

	/**
	 * 跳转客户信息查询页面
	 * 
	 * @param Customer 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	@RequestMapping("/toListCustomerPage")
	public String toListCustomerPage(CustomerEntity customer, HttpServletRequest request) {
		return "customer/customer_list";
	}

	/**
	 * 跳转新增页面
	 * @return string 跳转页面路径
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	@RequestMapping("/toAddCustomer")
	public String toAddCustomer(HttpServletRequest request, CustomerEntity customer) {
		request.setAttribute("opFlag", "add");
		request.setAttribute("customer", customer);
		return "customer/customer_form";
	}

	/**
	 * 跳转编辑页面
	 * @return string 跳转页面路径
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	@RequestMapping("/toUpdateCustomer")
	public String toUpdateCustomer(HttpServletRequest request) {
		// 编辑操作
		request.setAttribute("opFlag", "edit");
		long id = Long.valueOf(request.getParameter("id"));
		try {
			CustomerEntity customer = customerService.getCustomerById(id);
			if (null != customer) {
				Long companyId = customer.getCompanyId();
			}
			request.setAttribute("customer", customer);
		} catch (Exception e) {
			handleException("跳转编辑客户信息页面错误", logger, e);
		}
		return "customer/customer_form";
	}

	/**
	 * 跳转到选择客户页面
	 * @param customer
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月1日 下午7:16:16
	 */
	@RequestMapping("/toSelectCustomerPage")
	public String toSelectCustomerPage(CustomerEntity customer, HttpServletRequest request) {
		return "customer/customer_select";
	}

	/**
	 * 分页查询客户信息列表
	 * @param customer 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	@RequestMapping("/listCustomerPage")
	@ResponseBody
	public JSONGrid listCustomerPage(CustomerEntity customer, HttpServletRequest request) {
		int pageNum = 1;
		int numPerPage = 10000;

		if (StringUtil.isNotEmpty(request.getParameter("page")) && StringUtil.isNotEmpty(request.getParameter("rows"))) {
			pageNum = Integer.parseInt(request.getParameter("page").toString());
			numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		}

		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 公司名称
		paramMap.put("companName", request.getParameter("companyName"));
		// 客户名称
		paramMap.put("userName", request.getParameter("userName"));
		// 客户联系电话
		paramMap.put("mobile", customer.getMobile());
		// 客户级别
		paramMap.put("customerLevel", request.getParameter("customerLevel"));
		// 省份
		paramMap.put("provinceCode", request.getParameter("provinceCode"));
		// 城市
		paramMap.put("cityCode", request.getParameter("cityCode"));
		// 区域
		paramMap.put("areaCode", request.getParameter("areaCode"));
		
		
		paramMap.put("status", request.getParameter("status"));
		paramMap.put("startCreateTime", request.getParameter("startCreateTime"));
		paramMap.put("endCreateTime", request.getParameter("endCreateTime"));
		paramMap.put("companyInfo", customer.getCompanyInfo());
		

		try {
			PageBean pageBean = customerService.listCustomerPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询客户信息失败", logger, e);
		}
		return new JSONGrid();
	}
	
	
	
	
	/**
	 * 分页查询客户信息列表
	 * @author james
	 */
	@RequestMapping("/listCustomerPageForSecltor")
	@ResponseBody
	public JSONGrid listCustomerPageForSelector(CustomerEntity customer, HttpServletRequest request) {
		int pageNum = 1;
		int numPerPage = 10000;

		if (StringUtil.isNotEmpty(request.getParameter("page")) && StringUtil.isNotEmpty(request.getParameter("rows"))) {
			pageNum = Integer.parseInt(request.getParameter("page").toString());
			numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		}

		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 公司名称
		paramMap.put("companName", request.getParameter("companyName"));
		// 客户名称
		paramMap.put("userName", request.getParameter("userName"));
		// 客户联系电话
		paramMap.put("mobile", customer.getMobile());
		// 客户级别
		paramMap.put("customerLevel", request.getParameter("customerLevel"));
		// 省份
		paramMap.put("provinceCode", request.getParameter("provinceCode"));
		// 城市
		paramMap.put("cityCode", request.getParameter("cityCode"));
		// 区域
		paramMap.put("areaCode", request.getParameter("areaCode"));
		try {
			PageBean pageBean = customerService.listCustomerPageForSelector(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询客户信息失败", logger, e);
		}
		return new JSONGrid();
	}
	
	
	
	
	/**
	 * 查询客户信息列表
	 */
	@RequestMapping("/listCustomerForSelector")
	@ResponseBody
	public List<CustomerEntity> listCustomer(CustomerEntity customer, HttpServletRequest request) {
		List<CustomerEntity> customerList = null;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 客户电话
		paramMap.put("mobile", customer.getMobile());
		// 公司名称
		paramMap.put("companName", request.getParameter("companyName"));
		// 客户名称
		paramMap.put("userName", request.getParameter("userName"));
		// 客户联系电话
		paramMap.put("mobile", request.getParameter("mobile"));
		// 客户级别
		paramMap.put("customerLevel", request.getParameter("customerLevel"));
		// 省份
		paramMap.put("provinceCode", request.getParameter("provinceCode"));
		// 城市
		paramMap.put("cityCode", request.getParameter("cityCode"));
		// 区域 
		paramMap.put("areaCode", request.getParameter("areaCode"));
		try {
			customerList = customerService.listCustomer(paramMap);
		} catch (Exception e) {
			handleException("查询客户列表失败", logger, e);
		}
		return customerList;
	}
	
	
	/**
	 * 跳转客户选择页面
	 * @param reuqest
	 * @return
	 */
	@RequestMapping("/toCustomerSelector")
	public String toCustomerSelector(HttpServletRequest reuqest){
		return "/coupon/customer_selector";
	}
	

	/**
	 * 获取用户openID的用户列表
	 * 
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年12月4日 下午2:29:50
	 */
	@RequestMapping("/listWechatCustomerPage")
	@ResponseBody
	public JSONGrid listWechatCustomerPage(HttpServletRequest request) {
		int pageNum = 1;
		int numPerPage = 10000;

		if (StringUtil.isNotEmpty(request.getParameter("page")) && StringUtil.isNotEmpty(request.getParameter("rows"))) {
			pageNum = Integer.parseInt(request.getParameter("page").toString());
			numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		}

		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userName", request.getParameter("userName"));
		paramMap.put("mobile", request.getParameter("mobile"));
		paramMap.put("provinceCode", request.getParameter("provinceCode"));
		paramMap.put("cityCode", request.getParameter("cityCode"));
		paramMap.put("areaCode", request.getParameter("areaCode"));
		paramMap.put("customerLevel", request.getParameter("customerLevel"));

		try {
			PageBean pageBean = customerService.listWechatCustomerPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询客户信息失败", logger, e);
		}
		return new JSONGrid();
	}

	/**
	 * 新增或保存客户信息
	 * @param request 请求对象
	 * @param customerEntity 客户信息实体
	 * @return
	 * @author solin
	 * @date 2017-09-22 11:35:12
	 */
	@RequestMapping("/saveOrUpdateCustomer")
	@ResponseBody
	public Map<String, Object> saveCustomer(HttpServletRequest request, CustomerEntity customerEntity, String options) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			long theCustomerId = 0L;
			String id = request.getParameter("id");
			if (StringUtil.isNotEmpty(id)) { // 更新
				if ("audit".equals(request.getParameter("optType"))) { // 如果是注册审核
					customerEntity.setAuditor(this.getUserCode());
					customerEntity.setAuditTime(new Date());
				}
				theCustomerId = customerEntity.getId();
				result = customerService.updateCustomer(customerEntity);
				//审核的时候更改客户公司的客户等级和销售人员
				CustomerEntity customerInfo = customerService.getCustomerById(theCustomerId);
				if ("audit".equals(request.getParameter("optType")) && 
						(StringUtil.isNotEmpty(request.getParameter("customerLevel")) || 
								StringUtil.isNotEmpty(request.getParameter("salesmanCode")))) {
					//获取客户信息
					CompanyEntity conpanyEntity = new CompanyEntity();
					conpanyEntity.setId(customerInfo.getCompanyId());
					if (StringUtil.isNotEmpty(request.getParameter("customerLevel"))) {
						conpanyEntity.setCustomerLevel(Long.parseLong(request.getParameter("customerLevel")));
					}
					if (StringUtil.isNotEmpty(request.getParameter("salesmanCode"))) {
						conpanyEntity.setSalesmanCode(request.getParameter("salesmanCode"));
					}
					companyService.updateCompany(conpanyEntity);
				}
				// 如果审核通过，增加一个积分账户，如果有邀请者则邀请者获得邀请注册积分
				if (USER_APPROVE_STATUS.AGREE.getId().equals(customerEntity.getStatus())) {
					// 生成客户积分信息
					PointEntity point = new PointEntity();
					point.setCustomerId(theCustomerId);
					point.setPoint(BigDecimal.ZERO);
					point.setCreater(getUserName());
					pointService.savePoint(point);
					// 生成客户钱包信息
					WalletEntity wallet = new WalletEntity();
					wallet.setCustomerId(theCustomerId);
					wallet.setTotalMoney(BigDecimal.ZERO);
					wallet.setGetableMoney(BigDecimal.ZERO);
					wallet.setGetingMoney(BigDecimal.ZERO);
					walletService.saveWallet(wallet);
					//如果客户有邀请人则邀请人获得邀请注册积分
					if (StringUtil.isNotNull(customerInfo.getParentInvitationCode())) {
						try {
							CustomerEntity parentCustomer = customerService.getCustomerByInviationCode(customerInfo.getParentInvitationCode());
							if (null != parentCustomer) {
								BigDecimal registerPoint = BigDecimal.ZERO;
								List<KeyMapEntity> keyMapList = keyMapService.listKeyMap(PointConstants.REGISTER_POINT_KEY_TYPE);
								if (null != keyMapList && keyMapList.size() != 0) {
									registerPoint = new BigDecimal(keyMapList.get(0).getKeyValue());
								}
								pointService.doOperatePointCommon(parentCustomer.getId(), 
										PointOperateFlag.FLAG_ADD.getId(), PointOperateType.OPT_INVITE_REGISTER.getCode(),
										registerPoint, PointOperateType.OPT_INVITE_REGISTER.getName(), null, null, 
										customerInfo.getUserName(), false);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
				}
			} else { // 新增
				// 判断手机号是否存在
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("mobile", customerEntity.getMobile());
				List<CustomerEntity> customerList = customerService.listCustomer(param);
				if (customerList != null && customerList.size() > 0) {
					resultMap.put("code", "-1");
					resultMap.put("msg", "手机号已经存在");
					return resultMap;
				}

				// 创建人
				customerEntity.setCreater(this.getUserCode());
				customerEntity.setStatus(USER_APPROVE_STATUS.AGREE.getId()); //后台管理系统创建的客户状态默认为已审核通过
				// 保存客户信息到客户信息表
				theCustomerId = customerService.saveCustomer(customerEntity);
				result = (int) theCustomerId;

				// 生成新增客户的邀请码(限定5位)
				String invitationCode = new DecimalFormat("00000").format(theCustomerId);
				CustomerEntity updateCustomerEntity = new CustomerEntity();
				updateCustomerEntity.setId(theCustomerId);
				updateCustomerEntity.setInvitationCode(invitationCode);
				customerService.updateCustomer(customerEntity);
			}

			// 保存客户自定义属性
			if (theCustomerId > 0) {
				if (StringUtil.isNotEmpty(options)) {
					List<HashMap> optionList = JSONArray.parseArray(options, HashMap.class);
					List<CustomerExternalEntity> customerExternalList = new ArrayList<CustomerExternalEntity>();
					customerExternalService.deleteCustomerExternalByCustomerId(theCustomerId);
					for (int i = 0; i < optionList.size(); i++) {
						CustomerExternalEntity optionEntity = new CustomerExternalEntity();
						optionEntity.setCustomerId(theCustomerId);
						optionEntity.setFieldId(Long.parseLong(optionList.get(i).get("fieldId").toString()));
						optionEntity.setFieldValue(optionList.get(i).get("fieldValue").toString());
						customerExternalList.add(optionEntity);
					}
					if (customerExternalList.size() > 0) {
						customerExternalService.batchInsertCustomerExternal(customerExternalList);
					}
				}
			}

			// 将公司的地址设置为客户的默认地址
			if (null != customerEntity.getCompanyId()) {
				// 获取公司信息
				CompanyEntity companyInfo = companyService.getCompanyById(customerEntity.getCompanyId());
				if (StringUtil.isNotEmpty(companyInfo.getProvinceCode()) && StringUtil.isNotEmpty(companyInfo.getCityCode())
				        && StringUtil.isNotEmpty(companyInfo.getAreaCode()) && StringUtil.isNotEmpty(companyInfo.getAddress())) {
					// 判断该客户是否已有收货地址
					Map<String, Object> addressParam = new HashMap<String, Object>();
					addressParam.put("customerId", theCustomerId);
					addressParam.put("receiverName", customerEntity.getUserName());
					List<DeliveryAddressEntity> addressList = deliveryAddressService.listDeliveryAddress(addressParam);
					// 如果没有，则进行插入
					if (null == addressList || addressList.size() == 0) {
						DeliveryAddressEntity deliveryAddressInfo = new DeliveryAddressEntity();
						deliveryAddressInfo.setCustomerId(theCustomerId);
						deliveryAddressInfo.setReceiverName(customerEntity.getUserName());
						deliveryAddressInfo.setMobile(customerEntity.getMobile());
						deliveryAddressInfo.setProvinceCode(companyInfo.getProvinceCode());
						deliveryAddressInfo.setProvinceName(companyInfo.getProvinceName());
						deliveryAddressInfo.setCityCode(companyInfo.getCityCode());
						deliveryAddressInfo.setCityName(companyInfo.getCityName());
						deliveryAddressInfo.setAreaCode(companyInfo.getAreaCode());
						deliveryAddressInfo.setAreaName(companyInfo.getAreaName());
						deliveryAddressInfo.setStreetCode(companyInfo.getStreetCode());
						deliveryAddressInfo.setStreetName(companyInfo.getStreetName());
						deliveryAddressInfo.setAddress(companyInfo.getAddress());
						deliveryAddressInfo.setIsDefault(1);
						deliveryAddressInfo.setIsDelete(IS_DELETE.NOT_DELETE.getId());
						deliveryAddressInfo.setStatus(STATUS.ENABLED.getId());
						deliveryAddressInfo.setCreater(this.getUserCode());
//						deliveryAddressInfo.setCompanyId(getCompanyId());
						deliveryAddressInfo.setCompanyId(customerEntity.getCompanyId());
						deliveryAddressService.saveDeliveryAddress(deliveryAddressInfo);
					}
				}
			}

			resultMap.put("customerId", theCustomerId); // 人员信息ID主键
			resultMap.put("code", result > 1 ? 1 : result);
			resultMap.put("msg", "人员信息保存成功");
		} catch (Exception e) {
			resultMap.put("code", "0");
			resultMap.put("msg", "人员信息保存失败");
			handleException("添加客户信息失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 删除客户信息
	 * 
	 * @param request
	 * @param customerEntity
	 * @return
	 * @author: solin
	 * @date: 2017年9月26日 下午7:47:43
	 */
	@RequestMapping("/removeCustomer")
	@ResponseBody
	public Map<String, Object> removeCustomer(HttpServletRequest request, CustomerEntity customerEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			Long customerId = customerEntity.getId();
			result = customerService.deleteCustomerById(customerId);
			resultMap.put("code", result);
			resultMap.put("msg", "客户信息删除成功");
		} catch (Exception e) {
			resultMap.put("code", "0");
			resultMap.put("msg", "客户信息删除失败");
			handleException("客户信息删除失败", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 获取待审批数量
	 * @return
	 * @author: solin
	 * @date: 2017年12月27日 上午11:27:17
	 */
	@RequestMapping("/getPendingApprovalCount")
	@ResponseBody
	public Map<String, Object> getPendingApprovalCount() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Integer pendingApprovalCount = customerService.countPengdingApproval();
			resultMap.put("count", pendingApprovalCount);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "获取待审批数量失败");
		}
		return resultMap;
	}
	
	/**
	 * 业务员获取我的客户数
	 * @return
	 * @author: solin
	 * @date: 2017年12月31日 下午3:49:30
	 */
	@RequestMapping("/getMyCustomerCount")
	@ResponseBody
	public Map<String, Object> getMyCustomerCount(){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String salesmanId = String.valueOf(this.getUserId());
			Integer count = customerService.getMyCustomerCount(salesmanId);
			
			resultMap.put("count", count);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "获取业务员获取我的客户数失败");
		}
		return resultMap;
	}
	
	/**
	 * 获取已审批客户数
	 * @return
	 * @author: solin
	 * @date: 2018年1月7日 下午11:09:56
	 */
	@RequestMapping("/getAuditedCount")
	@ResponseBody
	public Map<String, Object> getAuditedCount() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Integer auditedCount = customerService.countAuditedCustomers();
			resultMap.put("count", auditedCount);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "获取已审批客户数量失败");
		}
		return resultMap;
	}
	
	/**
	 * 获取新增客户数
	 * @return
	 * @author: solin
	 * @date: 2018年1月8日 上午10:59:40
	 */
	@RequestMapping("/getNewCustomersCount")
	@ResponseBody
	public Map<String, Object> getNewCustomersCount() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			//获取定义新客户的天数
			String keyType = "daysOfNewCustomer";
			int days = 10; //默认10天
			List<KeyMapEntity> keyMapEntities = keyMapService.listKeyMap(keyType);
			if (keyMapEntities.size() > 0) {
				days = Integer.parseInt(keyMapEntities.get(0).getKeyValue());
			}
			
			Integer newCustomersCount = customerService.countNewCustomers(days);
			resultMap.put("count", newCustomersCount);
			resultMap.put(PublicStatus.RESULT_CODE, "1");
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "获取新增客户数量失败");
		}
		return resultMap;
	}

}
